package com.cheetah.start.common.plugin.log;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.cheetah.start.common.utils.MyDesensitizedUtil;
import com.cheetah.start.common.utils.MyIpUtil;
import com.cheetah.start.common.utils.MyServletUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.ThreadLocalUtil;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 控制台记录所有接口请求
 *
 * @author xjhmwj
 * @date 2021/1/25 14:12
 */
@Aspect
@Component
@Slf4j
public class ConsoleLogAspect {

    @Autowired
    private Ip2regionSearcher regionSearcher;

    @Pointcut("execution(public * com.cheetah.start..*.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {

    }

    @AfterThrowing(throwing = "e", pointcut = "webLog()")
    public void afterThrow(Throwable e) throws IOException {
        long start = System.currentTimeMillis();
        ThreadLocalUtil.put("start", start);
        ThreadLocalUtil.put("exception", true);
        MDC.put("logTrackId", IdUtil.simpleUUID().substring(0, 6));
        consoleLog(null, start, true);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
    }

    @Around("webLog()")
    public Object timing(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object;
        long start = System.currentTimeMillis();
        ThreadLocalUtil.put("start", start);
        ThreadLocalUtil.put("exception", false);
        MDC.put("logTrackId", IdUtil.simpleUUID().substring(0, 6));
        object = joinPoint.proceed();
        consoleLog(object, start, false);
        return object;
    }

    private void consoleLog(Object object, long start, boolean afterException) throws IOException {
        long l = System.currentTimeMillis() - start;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String contentType = request.getContentType();
        String param = MyServletUtil.getParam(request);
        if (contentType != null && contentType.contains(ContentType.JSON.getValue())) {
            BufferedReader reader = request.getReader();
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while (StrUtil.isNotBlank(line = reader.readLine())) {
                stringBuilder.append(line);
            }
            param = param + stringBuilder;
        }
        UserAgent parse = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String browserName = "";
        String version = "";
        OS os = null;
        if (parse != null) {
            Browser browser = parse.getBrowser();
            if (browser != null) {
                browserName = browser.getName();
            }
            version = parse.getVersion();
            os = parse.getOs();
        }

        // 处理完请求，返回内容
        StringBuilder s = new StringBuilder();
        if (object != null) {
            s.append(object);
            // 给太长的内容截取掉,日志太长不好看
            if (s.length() > 500) {
                s.delete(500, s.length() - 1);
                s.append(".....已截取");
            }
        }
        long l1 = System.nanoTime();
        String ipAddress = MyIpUtil.getIpNotHavePort(request);
        String address = regionSearcher.getAddress(ipAddress);

        if (afterException) {
            log.warn("接口地址:[{}],请求方式:[{}],参数:{}\nIP地址:[{}],其他信息:[{}]",
                    request.getRequestURI(),
                    request.getMethod() + "|" + request.getContentType(),
                    param,
                    ipAddress + "|" + address,
                    browserName + "|" + version + "|" + os
            );
        } else {
            log.info("\n┏━━━━━ 接口地址:{}\n┣ 方式:{}\n┣ 参数:{}\n┣ IP:{}\n┣ 其他:{}\n┣ 接口耗时:{}ms\n┣ 打印耗时:{}μs\n┣ 结果:{}\n┗━━━━━ ", request.getRequestURI(),
                    request.getMethod() + "|" + request.getContentType(),
                    param,
                    ipAddress + "|" + address,
                    browserName + "|" + version + "|" + os, l, (System.nanoTime() - l1) / 1000,
                    s);
        }
        if (l > 2000) {
            log.warn("注意:请求耗时过长,耗时:[{}]MS", l);
        }

    }


}
